package com.lzx.adx.report.controller.v1.ks;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.TaoBaoCovertKsEnums;
import com.lzx.adx.report.model.ks.request.KsReportRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品：淘宝联盟
 * 媒体：快手
 */
@RequestMapping("/ks/jy")
@RestController
@Slf4j
public class KsJyController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;


    /**
     * 接收快手媒体的点击监测数据
     *
     * @param ksReportRequest
     * @param request
     * @return
     */

    @GetMapping("/report")
    public ResponseEntity report(KsReportRequest ksReportRequest, HttpServletRequest request) {
        log.info("接收到快手到九游的点击请求参数为{}", JsonUtils.toJsonString(ksReportRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportKsReportDTO(ksReportRequest);
        reportDTO.setBizRequestId(IdUtil.fastUUID());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JSON.toJSONString(ksReportRequest));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(ksReportRequest.getDspId());
        String finalUrl = UrlUtil.covertKsJyUrl(accountDTO, reportDTO);
        log.info("账号为{},完整的快手到九游请求地址为{}", ksReportRequest.getDspId(), finalUrl);
        //2.2调用百度上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} 完整的快手到九游上报的接口，响应的结果为{}", ksReportRequest.getDspId(), body);
        return ResponseEntity.ok(new Result());
    }


    /**
     * 快手的回传
     *
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId, String conv_action) throws Exception {
        log.info("接收到九游回传到快手的请求流水号{},回调类型为{}", requestId, conv_action);
        if (StringUtils.isBlank(requestId) || StringUtils.isBlank(conv_action)) {
            log.info("接收到九游回传到快手的请求流水号或者事件类型为空,不做处理");
            return ResponseEntity.ok(new Result());
        }
        if (!"1".equals(conv_action)) {
            log.info("接收到九游回传到快手的请求流水号{}事件类型不合法，不做数据回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        String event_time = String.valueOf(System.currentTimeMillis());
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(conv_action);
            reportDTO.setResultTime(event_time);
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,conv_action);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.回调渠道，调用快手回传接口
        Map<String, Object> reqParams = new HashMap<>();
        reqParams.put("event_type", "1");
        reqParams.put("event_time", event_time);
        //组装参数和url
        String finalReqUrl = reportDTO.getCallback() + "&" + URLUtil.buildQuery(reqParams, StandardCharsets.UTF_8);
        log.info("账户id{}请求流水号{}九游回调快手的完整地址为：{}", reportDTO.getDspId(), requestId, finalReqUrl);
        String result = HttpUtil.createGet(finalReqUrl).execute().body();
        log.info("账户id{}请求流水号{}九游回回调快手的结果为：{}", reportDTO.getDspId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }


}
